﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
using OpenComposite.EII.Designer.Workflow.Forms;
using OpenComposite.EII.Repository;

namespace OpenComposite.EII.RepositoryUIs
{
	public partial class FormCreateNewMessageQueue : Forms.FormCreateNewBase
	{
		public FormCreateNewMessageQueue(IServiceProvider serviceProvider, RepositoryItemBase item, bool bAllowContinue)
			: base(serviceProvider, item, bAllowContinue)
		{
			InitializeComponent();
		}
		public FormCreateNewMessageQueue(IServiceProvider serviceProvider, RepositoryItemBase item, bool bAllowContinue, ItemType folderType)
			: base(serviceProvider, item, bAllowContinue, folderType)
		{
			InitializeComponent();
		}

		MessageQueue _queue = null;
		private MessageQueueEx MessageQueue
		{
			get { return this.RepositoryItem as MessageQueueEx; }
		}

		private void btnDiscover_Click(object sender, EventArgs e)
		{
			discover();
		}

		private void discover()
		{
			string path = txtPath.Text;
			if ( string.IsNullOrEmpty(path) ) {
				FormMsmqConfig form = new FormMsmqConfig();
				if ( form.ShowDialog() == DialogResult.OK ) {
					txtPath.Text = form.MessageQueuePath;
					_queue = new MessageQueue(form.MessageQueuePath);
				}
			} else {
				try {
					_queue = new MessageQueue(path);
					// CreateTime throws ArgumentOutOfRangeException if message queue was not found
					if ( _queue.CreateTime < DateTime.MaxValue ) _queue = null;
				} catch { _queue = null; }
				if ( _queue == null ) {
					MessageBox.Show("No message queue found!");
				}
			}
		}

		protected override void OnSaveClose(CancelEventArgs e)
		{
			if ( save() )
				base.OnSaveClose(e);
		}

		protected override void OnSaveContinue(CancelEventArgs e)
		{
			if ( save() )
				base.OnSaveContinue(e);
		}

		private bool save()
		{
			if ( _queue == null ) {
				MessageBox.Show("Invalid Message Queue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false;
			}
			if ( string.IsNullOrEmpty(txtPath.Text) || string.IsNullOrEmpty(txtPath.Text) ) {
				MessageBox.Show("Name and Path must be filled out!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
			MessageQueue.Name = _queue.Label;
			MessageQueue.Path = _queue.Path;
			MessageQueue.Description = textBox1.Text;
			MessageQueue.Save();
			return true;
		}
	}
}
